<?php

namespace app\command\controller;

use app\common\func\Lib;
use app\common\func\Tools;
use app\common\func\Transaction;
use app\common\model\EquipFigure;
use app\common\model\StandardMoney;
use app\common\model\transaction\Xyf;
use think\Config;
use think\Controller;
use think\Db;
use think\Env;
use think\Exception;
use think\Log;
use think\Request;

class Xyif extends Controller
{

    //商户绑定通知
    public function binds()
    {
        $param = request()->param();
        file_put_contents("bind_log.txt","-------------------".date("Y-m-d H:i:s")."(绑定数据)-----------------".PHP_EOL,FILE_APPEND | LOCK_EX);
        file_put_contents("bind_log.txt","数据:".json_encode($param).PHP_EOL,FILE_APPEND | LOCK_EX);
        $return = "FAILES";
        $origin = [];
        if (is_string($param)) {
            $origin = json_decode($param, true);
        }
        if (is_array($param)) {
            $origin = $param;
        }

        return "RECV_ORD_ID_" . $origin["reqSeqId"];

        $obj = new \DesEncrypt(Env::get("xyf.3DES"));
        $responce = $obj->decrypt($origin['data']);
        $data = json_decode($responce,true);

        $equip = Lib::getEquip($data['devId']);
        if($equip && $equip->binding_time == 0){
            try {
                $equip->user_info = json_encode([
                    "name" => $data['legalName'],
                    "id_card" => $data['idNo'],
                    "mobile" => $data['mobileNo'],
                ]);
                $equip->binding_time = strtotime($data['operateTime']);
                $equip->status = 1;
                $equip->save();
                //减少调拨机构库存
                Tools::updateStocks($equip->main_type, $equip->main_id, $equip->product_id, 2, [$data['devId']], "设备绑定减少库存");
                $return = "RECV_ORD_ID_" . $origin["reqSeqId"];
            }catch (\Exception $e){
                file_put_contents("bind_log.txt","-------------------".date("Y-m-d H:i:s")."-----------------".PHP_EOL,FILE_APPEND | LOCK_EX);
                file_put_contents("bind_log.txt","数据:".json_encode($data).PHP_EOL,FILE_APPEND | LOCK_EX);
                file_put_contents("bind_log.txt","错误信息:".$e->getMessage().PHP_EOL,FILE_APPEND | LOCK_EX);
            }
        }else{
            file_put_contents("bind_log.txt","-------------------".date("Y-m-d H:i:s")."-----------------".PHP_EOL,FILE_APPEND | LOCK_EX);
            file_put_contents("bind_log.txt","info:设备".$data['devId']."未找到".PHP_EOL,FILE_APPEND | LOCK_EX);
        }

        return $return;
    }

    //订单通知
    public function index()
    {
        $param = request()->param();
        $return = "FAILES";
        $origin = [];
        if (is_string($param)) {
            $origin = json_decode($param, true);
        }
        if (is_array($param)) {
            $origin = $param;
        }

        return "RECV_ORD_ID_" . $origin["reqSeqId"];

        $obj = new \DesEncrypt(Env::get("xyf.3DES"));
        $responce = $obj->decrypt($origin['data']);
        $data = json_decode($responce,true);

        try {
            if(is_array($data) && $data["transType"] != "CASH" && $data["bagentId"] == Env::get("xyf.bagent_id")){
                $orderNum = $data['ordId'];
                $rate = ($data['feeAmt'] && $data['transAmt']) ? bcdiv((string)($data['feeAmt'] * 100),(string)$data['transAmt'],2) : 0;

                $obj = new Xyf();
                $obj->bagent_id = $data['bagentId'];
                $obj->agent_id = $data['agentId'];
                $obj->merchant_name = $data['merchName'];
                $obj->merchant_id = $data['merchId'];
                $obj->order_num = $orderNum;
                $obj->sn = $data['devId'];
                $obj->transaction_result = $data['transStat'];
                $obj->transaction_type = $data['transType'];
                $obj->gather_type = $data['gatherType'];
                $obj->settle__type = $data['settleType'];
                $obj->transaction_amount = $data['transAmt'];
                $obj->transaction_commission = $data['feeAmt'];
                $obj->transaction_rate = $rate;
                $obj->card_type = $data['cardType'];
                $obj->trading_time = strtotime($data['transTime']);
                $obj->card_num = isset($data['cardNo']) ? $data['cardNo'] : "";
                $obj->is_active = $data['isActive'];
                $obj->active_amt = isset($data['actAmt']) ? $data['actAmt'] : 0;
                $obj->is_flow = (isset($data['isSim']) && $data['isSim'] == 1) ? 1 : 0;
                $obj->flow_amt = (isset($data['isSim']) && $data['isSim'] == 1) ? $data['simAmt'] : 0;
                $obj->save();

                $return = "RECV_ORD_ID_" . $origin["reqSeqId"];

                //设备统计信息
                $tranType = Lib::getTransactionTypeByCode($data['transType']);
                $rateId = Lib::getRateByName($rate);
                $cardTypeId = Tools::getCardTypeCode()[$data['cardType']]['id'];
                $channelId = Lib::getChannelByCode($data['gatherType']);

                $policy = Lib::getPolicyBySn($data['devId']);
                $cashAmount = 0;
                $standardAmount = 0;
                if($policy){
                    $rate = explode(",",$policy['rate_ids']);
                    $tran = explode(",",$policy['transaction_type_ids']);
                    $card = explode(",",$policy['card_type']);
                    $channel = explode(",",$policy['channel_ids']);
                    if(in_array($tranType->id,$tran) && in_array($rateId[0]->id,$rate) && in_array($cardTypeId,$card) && in_array($channelId->id,$channel)){
                        $cashAmount = $data['transAmt'];
                        $standardAmount = $data['transAmt'];
                    }

//                    if(in_array($tranType->id,$tran) && in_array($rateId->id,$rate) && in_array($cardTypeId,$card) && in_array($channelId->id,$channel)){
//                        $standardAmount = $data['transAmt'];
//                    }
                }

                $flowStatus = (isset($data['isSim']) && $data['isSim'] == 1) ? 1 : 0;

                $figure = Lib::getFigureBySn($data['devId']);
                if(!$figure){
                    $figure = new EquipFigure();
                    $figure->sn = $data['devId'];
                    $figure->flow_status = $flowStatus;
                    $figure->cash_amount = $cashAmount;
                    $figure->standard_amount = $standardAmount;
                    $amount = $data['transAmt'];
                    $count = 1;
                }else{
                    $figure->flow_status = $figure->flow_status ?: $flowStatus;
                    $figure->cash_amount += $cashAmount;
                    $figure->standard_amount += $standardAmount;
                    $amount = $figure->total_amount +  $data['transAmt'];
                    $count = $figure->total_count + 1;
                }
                $figure->total_amount = $amount;
                $figure->total_count = $count;
                $figure->last_time = strtotime($data['transTime']);
                $figure->save();

            }else{
                if($data["transType"] == "CASH"){
                    $return = "RECV_ORD_ID_" . $origin["reqSeqId"];
                }else{
                    file_put_contents("xyif_log.txt","-------------------数据异常：".date("Y-m-d H:i:s")."-----------------".PHP_EOL,FILE_APPEND | LOCK_EX);
                    file_put_contents("xyif_log.txt","data:".json_encode($data).PHP_EOL,FILE_APPEND | LOCK_EX);
                }
            }
        }catch (\Exception $e){
            file_put_contents("xyif_log.txt","-------------------".date("Y-m-d H:i:s")."-----------------".PHP_EOL,FILE_APPEND | LOCK_EX);
            file_put_contents("xyif_log.txt","data:".json_encode($data).PHP_EOL,FILE_APPEND | LOCK_EX);
            file_put_contents("xyif_log.txt","error:".$e->getMessage().PHP_EOL,FILE_APPEND | LOCK_EX);
        } finally {
            return $return;
        }
    }
}
